(function ($, window) {
    "use strict";
    (function () {
        var timeout;

        function triggerEvent() {
            $(document).trigger('ycmf-window-resized');
        }

        function fireOnce() {
            window.clearTimeout(timeout);
            timeout = window.setTimeout(triggerEvent, 200);
        }

        $(window).on('resize.ycmf-fire-once', fireOnce);
    }());

    $(document).ready(function () {
        var $document = $(document),
            $window = $(window),
            $body = $(document.body),
            $collapseMenu = $('#collapse-menu'),
            $wrap = $('#wrap'),
            $adminMenu = $('#admin-menu'),
            mobileEvent,
            stickyMenuActive = false,
            responsiveActive = false;

        $collapseMenu.on('click.collapse-menu', function () {
            var respWidth, state;

            if (window.innerWidth) {
                // window.innerWidth is affected by zooming on phones
                respWidth = Math.max(window.innerWidth, document.documentElement.clientWidth);
            } else {
                // IE < 9 doesn't support @media CSS rules
                respWidth = 992;
            }

            if (respWidth && respWidth < 991) {
                if ($body.hasClass('auto-fold')) {
                    $body.removeClass('auto-fold').removeClass('folded');
                    setUserSetting('unfold', 1);
                    setUserSetting('mfold', 'o');
                    state = 'open';
                } else {
                    $body.addClass('auto-fold');
                    setUserSetting('unfold', 0);
                    state = 'folded';
                }
            } else {
                if ($body.hasClass('folded')) {
                    $body.removeClass('folded');
                    setUserSetting('mfold', 'o');
                    state = 'open';
                } else {
                    $body.addClass('folded');
                    setUserSetting('mfold', 'f');
                    state = 'folded';
                }
            }

            $document.trigger('ycmf-collapse-menu', {state: state});
        });

        if ('ontouchstart' in window || /IEMobile\/[1-9]/.test(navigator.userAgent)) {

            // iOS Safari works with touchstart, the rest work with click
            mobileEvent = /Mobile\/.+Safari/.test(navigator.userAgent) ? 'touchstart' : 'click';

            // close any open submenus when touch/click is not on the menu
            $(document.body).on(mobileEvent + '.ycmf-mobile-hover', function (e) {
                if ($adminMenu.data('ycmf-responsive')) {
                    return;
                }

                if (!$(e.target).closest('#admin-menu').length) {
                    $adminMenu.find('li.has-sub.open-sub').removeClass('open-sub');
                }
            });

            $adminMenu.find('li.has-sub > a').on(mobileEvent + '.ycmf-mobile-hover', function (e) {
                var b, h, o, f, menutop, wintop, maxtop,
                    el = $(this),
                    parent = el.parent(),
                    m = parent.find('.has-sub'),
                    mName = el.find(' > .menu-name');

                if ($adminMenu.data('ycmf-responsive')) {
                    return;
                }

                // Show the sub instead of following the link if:
                //	- the submenu is not open
                //	- the submenu is not shown inline or the menu is not folded
                if (!parent.hasClass('open-sub') && (!parent.hasClass('menu-open') || parent.width() < 40 )) {
                    e.preventDefault();

                    menutop = parent.offset().top;
                    wintop = $window.scrollTop();
                    maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar

                    b = menutop + m.height() + 1; // Bottom offset of the menu
                    h = $wrap.height(); // Height of the entire page
                    o = 60 + b - h;
                    f = $window.height() + wintop - 50; // The fold

                    if (f < (b - o)) {
                        o = b - f;
                    }

                    if (o > maxtop) {
                        o = maxtop;
                    }

                    if (o > 1) {
                        m.css('margin-top', '-' + o + 'px');
                        if (mName.css('position') === 'absolute') {
                            mName.css('margin-top', '-' + o + 'px');
                        }
                    } else {
                        m.css('margin-top', '');
                        if (mName.css('position') === 'absolute') {
                            mName.css('margin-top', '');
                        }
                    }

                    $adminMenu.find('li.open-sub').removeClass('open-sub');
                    parent.addClass('open-sub');
                }
            });
        }

        $adminMenu.find('li.has-sub').hoverIntent({
            over: function() {
                var b, h, o, f, m = $(this).find('.sub-nav'),
                    menutop,
                    wintop,
                    maxtop,
                    top = parseInt(m.css('top'), 10),
                    mName = $(this).find('a > .menu-name');


                if (isNaN(top) /*|| top > -5*/) { // meaning the submenu is visible
                    return;
                }

                if ($adminMenu.data('ycmf-responsive')) {
                    // The menu is in responsive mode, bail
                    return;
                }

                menutop = $(this).offset().top;
                wintop = $window.scrollTop();
                maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar

                b = menutop + m.height() + 1; // Bottom offset of the menu
                h = $wrap.height(); // Height of the entire page
                o = 60 + b - h;
                f = $window.height() + wintop - 15; // The fold

                if (f < (b - o)) {
                    o = b - f;
                }

                if (o > maxtop) {
                    o = maxtop;
                }

                if (o > 1) {
                    m.css('margin-top', '-'+o+'px');
                    if (mName.css('position') === 'absolute') {
                        mName.css('margin-top', '-' + o + 'px');
                    }
                } else {
                    m.css('margin-top', '');
                    if (mName.css('position') === 'absolute') {
                        mName.css('margin-top', '');
                    }
                }

                $adminMenu.find('li.top-menu').removeClass('open-sub');
                $(this).addClass('open-sub');
            },

            out: function(){
                if ($adminMenu.data('ycmf-responsive')) {
                    // The menu is in responsive mode, bail
                    return;
                }

                $(this).removeClass('open-sub').find('.sub-nav').css('margin-top', '');
            },
            timeout: 200,
            sensitivity: 7,
            interval: 90
        });

        $adminMenu.on('focus.admin-menu', '.sub-nav a', function(e){
            if ($adminMenu.data('ycmf-responsive') ) {
                // The menu is in responsive mode, bail
                return;
            }

            $(e.target).closest('li.top-menu').addClass('open-sub');
        }).on('blur.admin-menu', '.sub-nav a', function(e){
            if ($adminMenu.data('ycmf-responsive')) {
                // The menu is in responsive mode, bail
                return;
            }

            $(e.target).closest('li.top-menu').removeClass('open-sub');
        });

        window.stickyMenu = {
            enable: function () {
                if (!stickyMenuActive) {
                    $document.on('ycmf-window-resized.sticky-menu', $.proxy(this.update, this));
                    $collapseMenu.on('click.sticky-menu', $.proxy(this.update, this));
                    this.update();
                    stickyMenuActive = true;
                }
            },

            disable: function () {
                if (stickyMenuActive) {
                    $window.off('resize.sticky-menu');
                    $collapseMenu.off('click.sticky-menu');
                    $body.removeClass('sticky-menu');
                    stickyMenuActive = false;
                }
            },

            update: function () {
                if ($window.height() > $adminMenu.height() + 32) {
                    if (!$body.hasClass('sticky-menu')) {
                        $body.addClass('sticky-menu');
                    }
                } else {
                    if ($body.hasClass('sticky-menu')) {
                        $body.removeClass('sticky-menu');
                    }
                }
            }
        };

        window.ycmfResponsive = {
            init: function () {
                var self = this;
                $document.on('ycmf-responsive-activate.ycmf-responsive',function () {
                    self.activate();
                }).on('ycmf-responsive-deactivate.ycmf-responsive', function () {
                    self.deactivate();
                });

                $('#admin-menu-toggle a').attr('aria-expanded', 'false');

                $('#admin-menu-toggle').on('click.ycmf-responsive', function (event) {
                    event.preventDefault();
                    $wrap.toggleClass('responsive-open');
                    if ($wrap.hasClass('responsive-open')) {
                        $(this).find('a').attr('aria-expanded', 'true');
                        //$adminMenu.find('a:first').focus();
                    } else {
                        $(this).find('a').attr('aria-expanded', 'false');
                    }
                });

                $adminMenu.on('click.ycmf-responsive', 'li.has-sub > a', function () {
                    if (!$adminMenu.data('ycmf-responsive')) {
                        return;
                    }

                    $(this).parent('li').toggleClass('selected');
                    event.preventDefault();
                });

                self.trigger();
                $document.on('ycmf-window-resized.ycmf-responsive', $.proxy(this.trigger, this));

                $window.on('load.ycmf-responsive', function () {
                    var width = navigator.userAgent.indexOf('AppleWebKit/') > -1 ? $window.width() : window.innerWidth;

                    if (width <= 767) {
                        self.disableSortables();
                    }
                });
            },

            activate: function () {
                window.stickyMenu.disable();

                if (!$body.hasClass('auto-fold')) {
                    $body.addClass('auto-fold');
                }

                $adminMenu.data('ycmf-responsive', 1);
                this.disableSortables();
            },

            deactivate: function () {
                window.stickyMenu.enable();
                $adminMenu.removeData('ycmf-responsive');
                this.enableSortables();
            },

            trigger: function () {
                var width;

                if (window.innerWidth) {
                    // window.innerWidth is affected by zooming on phones
                    width = Math.max(window.innerWidth, document.documentElement.clientWidth);
                } else {
                    // Exclude IE < 9, it doesn't support @media CSS rules
                    return;
                }

                if (width <= 767) {
                    if (!responsiveActive) {
                        $document.trigger('ycmf-responsive-activate');
                        responsiveActive = true;
                    }
                } else {
                    if (responsiveActive) {
                        $document.trigger('ycmf-responsive-deactivate');
                        responsiveActive = false;
                    }
                }

                if (width <= 480) {
                    this.enableOverlay();
                } else {
                    this.disableOverlay();
                }
            },

            enableOverlay: function () {

            },

            disableOverlay: function () {

            },

            disableSortables: function () {

            },

            enableSortables: function () {

            }
        };

        window.stickyMenu.enable();
        window.ycmfResponsive.init();
    });
    $(document).on({
        'pjax:start': function() {
            NProgress.start();
        },
        'pjax:end': function() {
            NProgress.done();
        }
    });
}(jQuery, window));